package system

import (
	"github.com/astaxie/beego/logs"
	"github.com/eclipse/paho.mqtt.golang"
	"regexp"
	"runtime/debug"
)

var routers = make(map[string]ControllerInterface)

// 添加路由
func AddRouter(path string, c ControllerInterface) {
	if _, ok := routers[path]; ok {
		return
	}
	routers[path] = c
}

// 匹配路由
func MatchRouter(client mqtt.Client, message mqtt.Message) {
	// 捕抓错误 防止mqtt客户端死掉
	defer func() {
		if err := recover(); err != nil {
			logs.Error("panic error:", err)
			debug.PrintStack()
		}
	}()

	for k, cli := range routers {
		reg := regexp.MustCompile(k)
		match := reg.FindStringSubmatch(message.Topic())
		if len(match) > 0 {
			cli.Init(client, message, match[1])
			cli.Exece(client, message, match[1])
			break
		}
	}
}
